package pack1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swim.entitybeans.RegisteredUser;
import swim.sessionbeans.AuthenticationRemote;
import swim.sessionbeans.FriendshipManagerRemote;
import swim.sessionbeans.SearchRemote;

/**
 * Servlet implementation class SearchServlet
 */
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			System.out.println("Ricerca");
			InitialContext jndiContext = new InitialContext();
			SearchRemote search = (SearchRemote) jndiContext.lookup("Search/remote");
			
			Set<RegisteredUser> result = new HashSet<RegisteredUser>();
			String searchstring = request.getParameter("searchstring");
			String type = request.getParameter("searchType");
			System.out.println("TYPE:"+type);
			if (type.equals("ability")) {
				result.addAll(search.searchForAbility(searchstring));
			} else {
				result.addAll(search.searchUser(searchstring));
			}			
			String filter = request.getParameter("searchFilter");
			if (filter!=null){
				FriendshipManagerRemote friendman = (FriendshipManagerRemote) jndiContext.lookup("FriendshipManager/remote");
				RegisteredUser loggeduser = (RegisteredUser)request.getSession().getAttribute("loggeduser");
				Vector<RegisteredUser> temp = new Vector<RegisteredUser>();
				for (RegisteredUser r: result) {
					if (friendman.isFriend(loggeduser.getId(), r.getId())) {
						temp.add(r);
					}
				}
				result.clear();
				result.addAll(temp);
			}
			request.setAttribute("searchresults", result);
			request.getRequestDispatcher("search.jsp").forward(request, response);				
		} catch (NamingException e) {
			e.printStackTrace();
		}	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
